package br.usp.ime.components.daos;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import br.com.caelum.vraptor.ioc.ApplicationScoped;
import br.com.caelum.vraptor.ioc.Component;
import br.usp.ime.entities.Topic;

@Component
@ApplicationScoped
public class TopicDao {
    private final Session session;

    public TopicDao(Session session) {
        this.session = session;
    }

    public void addTopic(Topic topic) {
        Transaction tx = this.session.beginTransaction();
        this.session.save(topic);
        tx.commit();
    }

    public void updateTopic(Topic topic) {
        if (topicExists(topic)) {
            Transaction tx = this.session.beginTransaction();
            this.session.merge(topic);
            tx.commit();
        }
    }

    public Topic loadTopic(Topic topic) {
        if (topic == null)
            return null;
        session.clear();
        return (Topic) session.createCriteria(Topic.class)
                .add(Restrictions.eq("id", topic.getId())).uniqueResult();
    }

    public void deleteTopic(Topic topic) {
        Topic deletedTopic = loadTopic(topic);
        if (deletedTopic != null) {
            Transaction tx = this.session.beginTransaction();
            this.session.delete(deletedTopic);
            tx.commit();
        }
    }

    @SuppressWarnings("unchecked")
    public List<Topic> listAllTopics() {
        return this.session.createCriteria(Topic.class).list();
    }
    
    private boolean topicExists(Topic topic) {
        return loadTopic(topic) != null;
    }
    
   
}
